<?php
class Answer_Service_Sample extends Phpfox_Service {
    function __construct()
    {
        $this->_sTable = Phpfox::getT('brodev_answer_category');
        $this->_sTableLevel = Phpfox::getT('brodev_answer_level');
        $this->_sFileUserGroup = Phpfox::getT('user_group');
        $this->_sFileCategory = PHPFOX_DIR . 'module/answer/include/static/sample.txt';
        $this->_sFileLevel = PHPFOX_DIR . 'module/answer/include/static/level.txt';
    }
    public function export() {
        $fExport = fopen($this->_sFileCategory, "w");
        $aCategories = Phpfox::getService('answer.category')->getListNoPage();
        $aCategories = $aCategories['data'];
        fwrite($fExport,json_encode($aCategories));
        fclose($fExport);
        $fExport = fopen($this->_sFileLevel, "w");
        $aLevels = Phpfox::getService('answer.level')->getListNoPage();
        $aLevels = $aLevels['data'];
        fwrite($fExport,json_encode($aLevels));
        fclose($fExport);
    }
    public function import() {
        $sCode = file_get_contents($this->_sFileCategory);
        $aData = json_decode($sCode, true);
        Phpfox::getService('answer.category')->deleteAll();
        foreach($aData as $iKey => $aCategory) {
            $iCategoryId = $this->database()->insert($this->_sTable, array(
                'id' => $aCategory['id'],
                'name' => $aCategory['name'],
                'parent_id' => $aCategory['parent_id']
            ));
        }
        // import level system
        $sCode = file_get_contents($this->_sFileLevel);
        $aData = json_decode($sCode, true);
        Phpfox::getService('answer.level')->deleteAll();
        $iPreviousGroup = 2;
        foreach($aData as $iKey => $aLevel) {
            $aUserGroup = array(
                'title' => $aLevel['group_name'],
                'inherit_id' => 2,
                'prefix' => "",
                'suffix' => ""
            );
            $iUserGroup = $this->database()
                ->select('user_group_id')
                ->from(Phpfox::getT('user_group'))
                ->where("title = '". $aUserGroup['title'] ."'")
                ->execute('getField');
            $iUserGroup = ($iUserGroup != 0) ? $iUserGroup : Phpfox::getService('user.group.process')->add($aUserGroup);

            $iLevel = $this->database()->insert($this->_sTableLevel, array(
                'group_id' => $iUserGroup,
                'previous_group' => $iPreviousGroup,
                'maxpoint' => $aLevel['maxpoint'],
                'minpoint' => $aLevel['minpoint'],
                'name' => $aLevel['name']
            ));
            $iPreviousGroup = $iUserGroup;
        }
    }
}